package com.jelly.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.google.gson.Gson;
import com.jelly.dto.Result;
import com.jelly.entity.WechatUser;
import com.jelly.service.WechatUserService;
import com.jelly.util.TokenUtil;
import com.jelly.vo.WechatSession;


@RestController
@RequestMapping("/wechat")
public class WechatController {

	@Value("${wechat.appid}")
	private String appid;

	@Value("${wechat.secret}")
	private String secret;
	@Resource
	private RestTemplate restTemplate;
	@Resource
	private WechatUserService wechatUserService;
	

	private static final String CODE_2_SESSION = "https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={js_code}&grant_type={grant_type}";

	@GetMapping("/jscode2session")
	public Result code2session(@RequestParam String code) {
		Map<String, String> map = new HashMap<>();
		map.put("appid", appid);
		map.put("secret", secret);
		map.put("js_code", code);
		map.put("grant_type", "authorization_code");
		String result = restTemplate.getForObject(CODE_2_SESSION, String.class, map);
		Gson gson = new Gson();
		WechatSession session = gson.fromJson(result, WechatSession.class);
		if (!ObjectUtils.isEmpty(session.getOpenid())) {
			String openId = session.getOpenid();
			WechatUser user = wechatUserService.findByOpenid(openId);
			if(user!=null) {
				//获取登录token
				String token = TokenUtil.sign(String.valueOf(user.getId()));
				return Result.success(token);
			}else {
				WechatUser chatUser = new WechatUser();
				BeanUtils.copyProperties(session, chatUser);
				chatUser.setUsername("微信用户"+openId.substring(0, 7));
				Long id = wechatUserService.insert(chatUser);
				//获取登录token
				String token = TokenUtil.sign(String.valueOf(id));
				return Result.success(token);
			}
		}
		return Result.error(result);
	}

}
